/*
 * Created by JFormDesigner on Sun Nov 09 17:29:10 CST 2025
 */

package com.yeban.bams.server;

import com.yeban.bams.service.Bank;

import java.awt.*;
import java.awt.event.*;
import java.util.Map;
import java.util.List;
import javax.swing.*;
import javax.swing.table.*;

/**
 * @author yeban
 */
public class DataPanel extends JPanel {

    private ATMServer atm;
    private DefaultTableModel totalModel, rankModel;

    public DataPanel(ATMServer atm) {
        this.atm = atm;
        initComponents();
        initTablesModels();
        bindInteractions();
        loadData();
    }

    // 初始化表格模型（设为不可编辑）
    private void initTablesModels() {
        // 总计表
        totalModel = new DefaultTableModel(new Object[]{"统计数据", "金额"}, 0) {
            @Override
            public boolean isCellEditable(int row, int column) { return false; }
        };
        table1.setModel(totalModel);

        // 资产排名表
        rankModel = new DefaultTableModel(new Object[]{"排名", "身份证号", "总资产"}, 0) {
            @Override
            public boolean isCellEditable(int row, int column) { return false; }
        };
        table2.setModel(rankModel);
    }

    private void loadData() {
        Bank bank = atm.bank;

        // ========== 总计表 ==========
        totalModel.setRowCount(0);
        Map<String, Double> totalStats = bank.getTotalStatistics();
        for (Map.Entry<String, Double> e : totalStats.entrySet()) {
            totalModel.addRow(new Object[]{e.getKey(), e.getValue()});
        }

        // ========== 资产排名 ==========
        rankModel.setRowCount(0);
        List<Map<String, Object>> ranks = bank.getAssetRank();
        for (Map<String, Object> r : ranks) {
            rankModel.addRow(new Object[]{r.get("rank"), r.get("personId"), r.get("total")});
        }
    }

    // 事件绑定：双击排行表 → 跳到账户面板（先清空再加载）
    private void bindInteractions() {
        table2.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    int row = table2.getSelectedRow();
                    if (row != -1) {
                        String personId = String.valueOf(table2.getValueAt(row, 1));
                        atm.accountPanel.clear(); // 清空目标页面
                        atm.accountPanel.loadAccountsByPersonId(personId); // 再加载数据
                        CardLayout layout = (CardLayout) atm.getContentPane().getLayout();
                        layout.show(atm.getContentPane(), "accountPanel");
                    }
                }
            }
        });
    }

    private void back(ActionEvent e) {
        atm.rankPanel.clear(); // 进入RankPanel前清空
        CardLayout cardLayout = (CardLayout) atm.getContentPane().getLayout();
        cardLayout.show(atm.getContentPane(), "rankPanel");
        atm.rankPanel.startRefresh();
    }

    private void allAccs(ActionEvent e) {
        // 停止表格刷新
        atm.rankPanel.stopRefresh();
        CardLayout cardLayout = (CardLayout) atm.getContentPane().getLayout();
        cardLayout.show(atm.getContentPane(), "accountPanel");
    }

    // 清空数据
    public void clearData() {
        if (totalModel != null) {
            totalModel.setRowCount(0);
        }
        if (rankModel != null) {
            rankModel.setRowCount(0);
        }
    }

    // 进入页面前清空并刷新
    public void reload() {
        clearData();
        loadData();
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        dataLabel = new JLabel();
        panel1 = new JPanel();
        dataTabbedPane = new JTabbedPane();
        summaryTable = new JPanel();
        scrollPane1 = new JScrollPane();
        table1 = new JTable();
        rankTable = new JPanel();
        scrollPane2 = new JScrollPane();
        table2 = new JTable();
        backButton = new JButton();
        allAccsButton = new JButton();

        //======== this ========
        setLayout(null);

        //---- dataLabel ----
        dataLabel.setText("\u6570  \u636e  \u7edf  \u8ba1");
        dataLabel.setHorizontalAlignment(SwingConstants.CENTER);
        dataLabel.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 30));
        add(dataLabel);
        dataLabel.setBounds(115, 40, 275, 65);

        //======== panel1 ========
        {
            panel1.setLayout(null);

            {
                // compute preferred size
                Dimension preferredSize = new Dimension();
                for(int i = 0; i < panel1.getComponentCount(); i++) {
                    Rectangle bounds = panel1.getComponent(i).getBounds();
                    preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                    preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
                }
                Insets insets = panel1.getInsets();
                preferredSize.width += insets.right;
                preferredSize.height += insets.bottom;
                panel1.setMinimumSize(preferredSize);
                panel1.setPreferredSize(preferredSize);
            }
        }
        add(panel1);
        panel1.setBounds(new Rectangle(new Point(45, 140), panel1.getPreferredSize()));

        //======== dataTabbedPane ========
        {

            //======== summaryTable ========
            {
                summaryTable.setLayout(null);

                //======== scrollPane1 ========
                {

                    //---- table1 ----
                    table1.setModel(new DefaultTableModel(
                        new Object[][] {
                            {"                    \u8d26\u6237\u4f59\u989d\u603b\u6570", null},
                            {"                    \u900f\u652f\u4f59\u989d\u603b\u6570", null},
                            {"                      \u8d37\u6b3e\u989d\u603b\u6570", null},
                        },
                        new String[] {
                            "\u6307\u6807\u540d\u79f0", "\u6570\u503c"
                        }
                    ));
                    {
                        TableColumnModel cm = table1.getColumnModel();
                        cm.getColumn(0).setPreferredWidth(150);
                        cm.getColumn(1).setPreferredWidth(100);
                    }
                    scrollPane1.setViewportView(table1);
                }
                summaryTable.add(scrollPane1);
                scrollPane1.setBounds(0, 0, 440, 385);

                {
                    // compute preferred size
                    Dimension preferredSize = new Dimension();
                    for(int i = 0; i < summaryTable.getComponentCount(); i++) {
                        Rectangle bounds = summaryTable.getComponent(i).getBounds();
                        preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                        preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
                    }
                    Insets insets = summaryTable.getInsets();
                    preferredSize.width += insets.right;
                    preferredSize.height += insets.bottom;
                    summaryTable.setMinimumSize(preferredSize);
                    summaryTable.setPreferredSize(preferredSize);
                }
            }
            dataTabbedPane.addTab("\u603b\u8ba1\u8868", summaryTable);

            //======== rankTable ========
            {
                rankTable.setLayout(null);

                //======== scrollPane2 ========
                {

                    //---- table2 ----
                    table2.setModel(new DefaultTableModel(
                        new Object[][] {
                            {null, null, null},
                            {null, null, null},
                        },
                        new String[] {
                            "\u6392\u540d", "\u8eab\u4efd\u8bc1\u53f7", "\u603b\u8d44\u4ea7"
                        }
                    ));
                    {
                        TableColumnModel cm = table2.getColumnModel();
                        cm.getColumn(0).setPreferredWidth(70);
                        cm.getColumn(1).setPreferredWidth(120);
                        cm.getColumn(2).setPreferredWidth(100);
                    }
                    scrollPane2.setViewportView(table2);
                }
                rankTable.add(scrollPane2);
                scrollPane2.setBounds(0, 0, 440, 385);

                {
                    // compute preferred size
                    Dimension preferredSize = new Dimension();
                    for(int i = 0; i < rankTable.getComponentCount(); i++) {
                        Rectangle bounds = rankTable.getComponent(i).getBounds();
                        preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                        preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
                    }
                    Insets insets = rankTable.getInsets();
                    preferredSize.width += insets.right;
                    preferredSize.height += insets.bottom;
                    rankTable.setMinimumSize(preferredSize);
                    rankTable.setPreferredSize(preferredSize);
                }
            }
            dataTabbedPane.addTab("\u8d44\u4ea7\u6392\u540d", rankTable);
        }
        add(dataTabbedPane);
        dataTabbedPane.setBounds(25, 110, 440, 425);

        //---- backButton ----
        backButton.setText("\u8fd4\u56de");
        backButton.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 14));
        backButton.addActionListener(e -> back(e));
        add(backButton);
        backButton.setBounds(370, 550, 100, 45);

        //---- allAccsButton ----
        allAccsButton.setText("\u8eab\u4efd\u8bc1\u4e0b\u6240\u6709\u8d26\u6237");
        allAccsButton.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 14));
        allAccsButton.addActionListener(e -> allAccs(e));
        add(allAccsButton);
        allAccsButton.setBounds(210, 550, 150, 45);

        setPreferredSize(new Dimension(500, 650));
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    private JLabel dataLabel;
    private JPanel panel1;
    private JTabbedPane dataTabbedPane;
    private JPanel summaryTable;
    private JScrollPane scrollPane1;
    private JTable table1;
    private JPanel rankTable;
    private JScrollPane scrollPane2;
    private JTable table2;
    private JButton backButton;
    private JButton allAccsButton;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on
}


